#include "register_user_protocol.hpp"
#include "../core/di_container.hpp"
#include "../common/logger.hpp"
#include "../core/game_server.hpp"

namespace protocols {

RegisterUserProtocol::RegisterUserProtocol() {
    Logger::info("RegisterUserProtocol created");
    user_service_ = DIContainer::get<service::UserService>();
}

RegisterUserProtocol::~RegisterUserProtocol() {
    Logger::info("RegisterUserProtocol destroyed");
}

bool RegisterUserProtocol::validate(GameServer& game_server, const nlohmann::json& message, uint32_t session_id) {
    if (!message.contains("username") || !message.contains("password")) {
        Logger::error("RegisterUserProtocol validate: username or password not found");
        return false;
    }
    return true;
}

void RegisterUserProtocol::process(GameServer& game_server, const nlohmann::json& message, uint32_t session_id) {
    Logger::info("RegisterUserProtocol process");
    // 注册用户 
    std::string username = message["username"];
    std::string password = message["password"];
    bool result = user_service_->register_user(username, password);
    if (!result) {
        Logger::error("RegisterUserProtocol process: register user failed");
        nlohmann::json response = {
            {"type", "register_user"},
            {"status", 201},
            {"message", "register user failed"}
        };
        game_server.send_message(session_id, response);
        return;
    }

    // 注册成功 (包含用户名)
    Logger::info("RegisterUserProtocol process: register user success, username: {}", username);
    nlohmann::json response = {
        {"type", "register_user"},
        {"status", 200},
        {"message", "register user success"},
        {"username", username}
    };
    game_server.send_message(session_id, response);
}

} // namespace protocols